/**************************************************************
 *   File:	FormatBuffer.h
 * Author:	Andrew Thorpe
 *  Brief:	Used to format strings in a nicer way than printf,
 *			should be safe from buffer overruns.
 * 			Can be used with either:
 * 				FormatBuffer<512> MyString("hello '%s'\n", "string");
 *				Format MyString("hello '%s' %d\n", "string", 123);
 **************************************************************/
#ifndef _FOSSIL_FORMATBUFFER_H
#define _FOSSIL_FORMATBUFFER_H

#include <stdio.h>
#include <stdarg.h>

namespace Fossil
{
	template<int size> 
	class FormatBuffer
	{
	public:
		FormatBuffer() : m_Remaining(size)
		{
			m_Buffer[0] = 0;
		}

		FormatBuffer(const char* fmt, ...) :  m_Remaining(size)
		{
			va_list args;
			va_start(args, fmt);
			vsprintf_s(m_Buffer, m_Remaining, fmt, args);
			va_end(args);
		}

		~FormatBuffer()
		{
		}

		const char* Print(const char* fmt, ...)
		{
			if(0 <= m_Remaining)
			{
				va_list args;
				va_start(args, fmt);
				int printed = vsprintf_s(m_Buffer, m_Remaining, fmt, args);
				va_end(args);

				if(printed > 0)//vsprintf_s returns -1 on err
				{
					m_Remaining -= printed;
				}
			}
			return m_Buffer;
		}

		//Const and non-const returns
		operator const char*()	const { return (const char*)m_Buffer; }
		operator char*()		const { return (char*)m_Buffer; }

	private:
		int		m_Remaining;
		char	m_Buffer[size];
	};

	// Provide a default type
	// 1Kb should be enough
	typedef FormatBuffer<1024>	Format;

};

#endif//_FOSSIL_FORMATBUFFER_H
